package com.example.onlineeducation.ui.offline

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import com.example.onlineeducation.App
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.OfflineExamConstants
import com.example.onlineeducation.data.entity.OfflineExamDetailTranEntity
import com.example.onlineeducation.data.model.OfflineExamRecordDataModel
import com.example.onlineeducation.databinding.OfflineExamRecordListActivityBinding
import com.example.onlineeducation.databinding.OfflineExamRecordListItemBinding
import com.example.onlineeducation.viewmodel.OfflineExamRecordListVM
import com.yc.jetpacklib.extension.*
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.recycleView.YcPagingDataAdapter
import com.yc.jetpacklib.refresh.YcRefreshBaseUtil
import com.yc.jetpacklib.refresh.YcRefreshSpecialPagingUtil
import com.yc.jetpacklib.ui.YcScanQrcodeActivity
import com.yc.jetpacklib.utils.YcResources
import com.yc.jetpacklib.utils.showErrorDialog
import com.yc.jetpacklib.utils.showSingleBtnDialog
import com.yc.jetpacklib.widget.dialog.YcCommonDialog

/**
 * Creator:
 * Date: 2022/4/1 15:10
 * UseDes:线下考试记录列表
 */
@SuppressLint("SetTextI18n")
class OfflineExamRecordListActivity : BaseActivity<OfflineExamRecordListActivityBinding>(OfflineExamRecordListActivityBinding::inflate) {
    private val mViewModel by ycViewModels<OfflineExamRecordListVM>()
    private var mProId: String? = null
    private var mExamId: String? = null
    private var mStartTime: String? = null
    private var mEndTime: String? = null
    private var mTotalScore: String = "0"
    private lateinit var mRefreshUtil: YcRefreshBaseUtil<OfflineExamRecordDataModel>
    private lateinit var scanQrcodeLauncher: ActivityResultLauncher<Intent>
    private lateinit var detailLauncher: ActivityResultLauncher<Intent>
    private val dialog by lazy {
        YcCommonDialog(this, this)
    }

    companion object {
        private const val KEY_EXAM_ID = "key_exam_id"
        private const val KEY_EXAM_NAME = "key_exam_name"
        private const val KEY_START_TIME = "key_start_time"
        private const val KEY_END_TIME = "key_end_time"
        private const val KEY_TOTAL_SCORE = "key_total_score"

        @JvmStatic
        fun newInstance(context: Context, id: String, examName: String, startTime: String?, endTime: String?, totalScore: String) {
            val intent = Intent(context, OfflineExamRecordListActivity::class.java).apply {
                putExtra(KEY_EXAM_ID, id)
                putExtra(KEY_EXAM_NAME, examName)
                putExtra(KEY_START_TIME, startTime)
                putExtra(KEY_END_TIME, endTime)
                putExtra(KEY_TOTAL_SCORE, totalScore)
            }
            context.startActivity(intent)
        }
    }

    private val mAdapter: YcPagingDataAdapter<OfflineExamRecordDataModel, OfflineExamRecordListItemBinding>
            by YcPagingDataAdapter.ycLazyInitApply(OfflineExamRecordListItemBinding::inflate, OfflineExamRecordDataModel.diffCallback) {
                mOnUpdate = {
                    ivAvatar.ycLoadImageNetCircle(it.avatar, R.drawable.ic_avatar2, R.drawable.ic_avatar2)
                    tvName.text = it.userName
                    tvWorkType.text = it.workType
                    tvState.text = OfflineExamConstants.showResultText(it.state)
                    tvState.background = YcResources.getDrawable(OfflineExamConstants.showResultBg(it.state))
                    tvExamScores.text = "${it.examScores.ycToNoEmpty("0")}分"
                    tvAnswerTime.text = "${it.answerTime.ycToNoEmpty(0)}分钟"
                    tvExamDate.text = it.examDate.ycToNoEmpty()
                }
                mItemClick = {
                    if (it.id.ycIsNotEmpty()) {
                        OfflineExamDetailActivity.newInstance(
                            this@OfflineExamRecordListActivity,
                            OfflineExamDetailTranEntity(
                                it.id!!, it.userName, it.workType, it.examScores, it.answerTime, it.examDate,
                                it.groupName, it.webPathList, mStartTime, mEndTime, mTotalScore
                            ), detailLauncher
                        )
                    } else {
                        showToast("考试记录Id无效,请联系管理员")
                    }
                }
            }

    override fun OfflineExamRecordListActivityBinding.initView() {
        intent.apply {
            mExamId = getStringExtra(KEY_EXAM_ID)!!
            actionBar.setTitle(getStringExtra(KEY_EXAM_NAME) ?: "考试")
            mStartTime = getStringExtra(KEY_START_TIME)
            mEndTime = getStringExtra(KEY_END_TIME)
            mTotalScore = getStringExtra(KEY_TOTAL_SCORE) ?: "0"
        }
        App.mInstant.mViewModel.mProInfoEntity.observe {
            mProId = it!!.proId
        }
        scanQrcodeLauncher = ycCreateResultLauncher {
            if (it.data != null) {
                val result: String = it.data?.getStringExtra(YcScanQrcodeActivity.SCAN_RESULT) ?: ""
                if (result.ycIsEmpty()) {
                    showErrorDialog(dialog, "扫描结果为空，请再试一次")
                    return@ycCreateResultLauncher
                } else {
                    mViewModel.getOfflineExamDetail(mProId!!, mExamId!!, result)
                }
            }
        }
        detailLauncher = OfflineExamDetailActivity.getLauncher(this@OfflineExamRecordListActivity) {
            mRefreshUtil.startRefresh()
        }
        ivScanQrcode.setOnClickListener {
            YcScanQrcodeActivity.newInstance(this@OfflineExamRecordListActivity, scanQrcodeLauncher, R.drawable.shape_bg_scan_qrcode_frame)
        }

        ivSearch.setOnClickListener {
            OfflineExamRecordSearchActivity.newInstance(this@OfflineExamRecordListActivity, mExamId, mStartTime, mEndTime, mTotalScore)
        }
        rv.apply {
            adapter = mAdapter
            ycInitLinearLayoutManage()
        }
        mRefreshUtil = YcRefreshSpecialPagingUtil<OfflineExamRecordDataModel>(this@OfflineExamRecordListActivity)
            .build(mAdapter, srl, rv, fl) {
                mRefreshCall = {
                    getData()
                }
            }

        mViewModel.apply {
            mOfflineExamRecordList.observe {
                mRefreshUtil.acSetPagingData(it)
            }

            mOfflineExamDetails.observe { ycResult ->
                ycResult.doSuccess {
                    if (it != null) {
                        if (it.id.ycIsNotEmpty()) {
                            OfflineExamDetailActivity.newInstance(
                                this@OfflineExamRecordListActivity,
                                OfflineExamDetailTranEntity(
                                    it.id!!, it.userName, it.workType, it.examScores, it.answerTime, it.examDate,
                                    it.groupName, it.webPathList, mStartTime, mEndTime, mTotalScore
                                ), detailLauncher
                            )
                        } else {
                            showToast("考试记录Id无效,请联系管理员")
                        }
                    } else {
                        showSingleBtnDialog(mDialog, "该考试暂无此人员考试信息")
                    }
                }.ycShowNetError()
            }
        }

    }

    private fun getData() {
        mViewModel.getOfflineExamRecordListPager(mProId!!, mExamId!!)
    }
}